package com.muyan.sys.webscoket.server;

import com.muyan.sys.common.core.redis.RedisCache;
import com.muyan.sys.framework.web.service.TokenService;
import com.muyan.sys.webscoket.service.ChatGroupService;
import com.muyan.sys.webscoket.service.ServerInstanceManager;
import com.muyan.sys.webscoket.util.ChannelManager;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class WebSocketServer {

    @Value("${websocket.port:8888}")
    private int port;
    @Autowired
    private TokenService tokenService;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    
    @Autowired
    private RabbitTemplate rabbitTemplate;
    
    @Autowired
    private ChannelManager channelManager;

    @Autowired
    private ChatGroupService chatGroupService;

    @Autowired
    private ServerInstanceManager serverInstanceManager;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private  WebSocketHandshakeHandler handshakeHandler;
    @PostConstruct
    public void start() throws Exception {
        bossGroup = new NioEventLoopGroup(1);
        // 根据CPU核心数设置worker线程数
        workerGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2);

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            
                            // HTTP 编解码器
                            pipeline.addLast(new HttpServerCodec());
                            // 支持大数据流
                            pipeline.addLast(new ChunkedWriteHandler());
                            // HTTP 消息聚合器
                            pipeline.addLast(new HttpObjectAggregator(64 * 1024));
                            // 自定义握手处理器（用于认证）
                            pipeline.addLast(handshakeHandler);
                            // 空闲检测
                            pipeline.addLast(new IdleStateHandler(60, 0, 0, TimeUnit.SECONDS));
                            // WebSocket 协议处理
                            pipeline.addLast(new WebSocketServerProtocolHandler("/ws", null, true));
                            // 自定义消息处理器
                            pipeline.addLast(new WebSocketMessageHandler(rabbitTemplate, channelManager, serverInstanceManager,redisCache,chatGroupService,tokenService));
                        }
                    });

            Channel channel = bootstrap.bind(port).sync().channel();
            log.info("WebSocket 服务器启动成功，监听端口: {}", port);
            channel.closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    @PreDestroy
    public void stop() {
        if (bossGroup != null) {
            bossGroup.shutdownGracefully();
        }
        if (workerGroup != null) {
            workerGroup.shutdownGracefully();
        }
    }
} 